import React, { useEffect } from "react";
import { useNavigate } from "react-router-dom";
import {
  Button,
  Form,
  Image as MyImage,
  ImageUploader,
  Input,
  Popup,
  Toast,
} from "antd-mobile";
// import CropImage from "./CropImage";
import $fetch from "../../../../utils/app/$fetch";
import $reducer from "../../../../utils/app/$reducer";
import $readFile from "../../../../utils/app/$readFile";
import CropImage from "../../../../utils/ui/CropImage";
import { ReactComponent as CoreIcon } from "../../../../asset/imgs/core.svg";
import $getQuery from "../../../../utils/app/$getQuery";
import { CloseOutline } from "antd-mobile-icons";
import "./style.scss";

const bg2: any = require("../../../../asset/imgs/personal_bg2.jpg");

const iconColor = getComputedStyle(document.documentElement)
  .getPropertyValue("--logoColor")
  .trim();

export default function PersonalComponent() {
  const [form]: any = Form.useForm();
  const navigate: any = useNavigate();
  const initState: any = {
    coreList: [],
    showEdit: false,
    name: "",
    avatar: [{ url: "" }],
    showCropper: false,
    backImg: "",
    img: "",
    isLoaded: false,
    currentImg: ''
  };

  const [state, dispatch] = $reducer({ ...initState });

  // 调用接口请求数据
  useEffect(() => {
    getBg();
    initPage();
  }, []);

  const getBg = () => {
    const $params: any = $getQuery();
    const { groupId = "" } = { ...$params };
    const groupIdStrorage = localStorage.getItem("groupId");
    const groupIdCurrent = groupId || groupIdStrorage;
    var backImg: any;
    switch (groupIdCurrent) {
      case "1":
        backImg = bg2;
        break;
    }
    dispatch({ backImg });
  };

  const initPage = async () => {
    const res: any = await $fetch(
      "/customerPoint/customerPointInf",
      {},
      { noGroupId: "no" }
    );
    dispatch({ coreList: res, isLoaded: true, img: res?.avatar });
  };

  const handleLogout = async () => {
    localStorage.removeItem("token");
    localStorage.removeItem("roleType")
    await $fetch("/customer/logout", {}, { method: "post", noGroupId: "no" });
    window.location.replace("/#/login");
  };

  const beforeUpload = async (file: File) => {
    if (file.size > 1024 * 1024 * 10) {
      Toast.show("请选择小于 10M 的图片");
      return null;
    } else {
      let imageDataUrl = await $readFile(file);
      dispatch({ showCropper: true, avatar: file, image: imageDataUrl });
    }
    return null;
  };

  const handleUpload: any = async (file: any) => {
    // try {
    //   const formData = new FormData();
    //   if (file instanceof File) {
    //     formData.append("file", file);
    //     const res: any = await $fetch("/minio/upload", formData, {
    //       method: "post",
    //       noGroupId: "no",
    //       dataType: "form",
    //       loading: false,
    //     });
    //     dispatch({ avatar: [{ url: res?.url }] });
    //     return { url: res?.url };
    //   }
    // } catch (error) {
    //   console.log(error, "______error");
    // }
  };

  const onSubmit = async () => {
    // let { name = "", avatarnone = "" } = form.getFieldsValue();
    // var avatar = avatarnone[0]?.url;
    const name = state?.name || state?.coreList?.customerName;
    const avatar = state?.avatar?.[0]?.url || state?.coreList?.avatar;
    if (
      state?.coreList?.customerName === name &&
      state?.coreList?.avatar === avatar
    ) {
      dispatch({ showEdit: false, name: "", avatar: "" });
      return;
    }
    try {
      await $fetch(
        `/customer/updateInfo?avatar=${avatar}${name ? `&name=${name}` : ""}`,
        {},
        { method: "post", noGroupId: "no" }
      );
      Toast.show("修改成功");
      dispatch({ showEdit: false, name: "", avatar: "", currentImg: state?.img });
      form.resetFields();
      await initPage();
    } catch (error) {
      console.log(error, "_____error");
    }
  };

  if (!state?.isLoaded) return null;
  
  return (
    <div className="that_personal_wraper">
      <div style={{ position: "absolute", zIndex: "-1", width: '100%' }}>
        <MyImage width="100%" height="5.15rem" src={state?.backImg || ''} />
      </div> 

      <div className="item_top">
        <div className="avatar">
          <MyImage
            src={state?.img ? state.img : state?.coreList?.avatar}
            height="1.6rem"
            width="1.6rem"
            fit="cover"
          />
          <div className="info">
            <div
              className="name"
              onClick={() => {
                form.setFieldsValue({
                  name: state?.coreList?.customerName,
                  avatarnone: [{ url: state?.coreList?.avatar }],
                  // avatar: [{ url: state?.coreList?.avatar }],
                });
                dispatch({
                  showEdit: true,
                  img: state?.coreList?.avatar,
                });
              }}
            >
              <h4>{state?.coreList?.customerName}</h4>
              <div></div>
            </div>
            <div>{state?.coreList?.memberId ? "fanclub会员" : ""}</div>
          </div>
        </div>
        <div className="personal_account">
          <div>
            <CoreIcon width=".53rem" height=".53rem" fill={iconColor} />
            <div>我的积分：{state?.coreList?.customerPoint || 0}</div>
          </div>
          <div
            className="to_shop"
            onClick={() => {
              navigate("/core/list", {
                state: { customerPoint: state?.coreList?.customerPoint },
              });
            }}
          >
            积分商城
          </div>
        </div>
      </div>
      <ul className="item_content">
        <li>
          <div
            onClick={() => {
              navigate("/order/list");
            }}
          >
            <img src={require("@/asset/imgs/personal/orderList.png")}></img>
          </div>
          <div>全部订单</div>
        </li>
      </ul>
      <div className="item_logout" onClick={() => handleLogout()}>
        <button>退出登录</button>
      </div>
      <Popup
        className="personal_edit_popup"
        showCloseButton
        visible={state?.showEdit}
        onClose={() => {
          form.resetFields();
          dispatch({ showEdit: false, name: "", avatar: "", img: '' });
        }}
      >
        <div className="item_edit">
          <Form
            layout="horizontal"
            form={form}
            footer={
              <>
                <Button
                  onClick={onSubmit}
                  block
                  type="submit"
                  color="primary"
                  shape="rounded"
                >
                  确定修改
                </Button>
              </>
            }
          >
            <Form.Item name="name" label="昵称">
              <Input
                value={state?.name}
                placeholder="请输入昵称"
                clearable
                onChange={(e: any) => {
                  dispatch({ name: e });
                }}
              />
            </Form.Item>
            <Form.Item name="avatar" label="头像">
              {state?.img ? (
                <div className="crooped_wraper">
                  <div className="cropped_img">
                    <img src={state?.img} alt="" />
                    <div onClick={() => dispatch({ img: "", avatar: [] })}>
                      <CloseOutline />
                    </div>
                  </div>
                </div>
              ) : (
                <ImageUploader
                  onChange={(file: any) => {
                    dispatch({ avatar: file });
                  }}
                  beforeUpload={beforeUpload}
                  multiple={false}
                  upload={handleUpload}
                  maxCount={1}
                />
              )}
              {/* <ImageUploader
                value={state?.avatar || [{ url: "" }]}
                onChange={(file: any) => {
                  dispatch({ avatar: file });
                }}
                multiple={false}
                upload={handleUpload}
                beforeUpload={beforeUpload}
                maxCount={1}
              /> */}
            </Form.Item>
          </Form>
        </div>
        {state?.showCropper && (
          <CropImage
            visible={state?.showCropper}
            src={state?.image}
            form={form}
            avatar={state?.avatar}
            dispatch={dispatch}
            from="personal"
          />
        )}
      </Popup>
    </div>
  );
}
